package com.ruoyi.web.controller.Upload;

import cn.hutool.core.collection.IterUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.system.domain.entity.Upload;
import com.ruoyi.system.service.IUploadService;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author GE-LV5
 * @create 2023/2/27 15:24
 */
@Api(tags = "文件上传")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@Slf4j
@RequestMapping("/system/upload")
public class UploadController extends BaseController {
    private String prefix = "system/upload";

    @Autowired
    private IUploadService uploadService;

    @GetMapping()
    public String upload() {
        return prefix + "/upload";
    }

    public static void main(String[] args) {
        UUID uuid = UUID.randomUUID();
        System.out.println(uuid);
    }

    /**
     * 查看文件
     *
     * @param upload
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:upload:list')")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Upload upload) {
        startPage();
        List<Upload> uploads = uploadService.selectUploadList(upload);
        return getDataTable(uploads);
    }


    /**
     * 修改文件上传
     *
     * @param id
     * @param mmap
     * @return
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        Upload upload = uploadService.selectUploadById(id);
        mmap.put("upload", upload);
        return prefix + "/edit";

    }

    /**
     * 修改文件
     *
     * @param upload
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:upload:edit')")
    @Log(title = "文件上传", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Upload upload) {
        return toAjax(uploadService.updateUpload(upload));
    }


    /**
     * 导出文件上传列表
     *
     * @param upload
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:upload:export')")
    @Log(title = "文件上传", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Upload upload) {
        List<Upload> uploads = uploadService.selectUploadList(upload);
        ExcelUtil<Upload> uploadExcelUtil = new ExcelUtil<>(Upload.class);
        return uploadExcelUtil.exportExcel(uploads, "文件上传数据");
    }

    /**
     * 删除文件上传
     *
     * @param
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:upload:remove')")
    @Log(title = "文件上传", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(uploadService.deleteUploadByIds(ids));
    }


    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存文件上传
     *
     * @param upload
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:upload:addSave')")
    @Log(title = "文件上传", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Upload upload) {
        return toAjax(uploadService.insertUpload(upload));
    }


    /**
     * 新增文件上传
     *
     * @param
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:upload:insert')")
    @Log(title = "文件上传", businessType = BusinessType.INSERT)
    @PostMapping("/insert")
    @ResponseBody
    public AjaxResult remove(Upload upload) {
        return toAjax(uploadService.insertUpload(upload));
    }


    /**
     * 图片上传
     */
    @PostMapping("/img")
    public AjaxResult img(@RequestParam("file") List<MultipartFile> files)
    {
        if(IterUtil.isNotEmpty(files)){
            List<String> list = new ArrayList<>();
            files.stream().forEach(file->{
                if (!file.isEmpty())
                {
                    String avatar = null;
                    try {
                        avatar = FileUploadUtils.upload(RuoYiConfig.getImgPath(), file);
                        list.add(avatar);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            });
            AjaxResult ajax = AjaxResult.success();
            ajax.put("imgUrl", list);
            return ajax;
        }
        return AjaxResult.error("上传图片异常，请联系管理员");
    }


    @Value("${ruoyi.profileImg}")
    private String profileImg;

    /**
     * 删除指定文件夹或文件
     * @param path 文件夹或文件路径
     * @return Boolean 删除成功返回true，删除失败返回false。
     */
    @PostMapping("/delete")
    public AjaxResult uploadCustomPathFile(@RequestBody Map<String,List<String>> path){
        List<String> list = path.get("path");
        if(IterUtil.isNotEmpty(list)){
            list.stream().forEach(i->{
                boolean b = FileSystemUtils.deleteRecursively(new File(profileImg+i));
            });
        }
        return AjaxResult.success("删除成功");
    }



    @Service
    public class UploadService {

        // 保存图片的方法
        public String save(MultipartFile file) throws IOException {
            // 生成随机的文件名
            String filename = UUID.randomUUID().toString() + ".jpg";

            // 保存文件到本地磁盘
            File dest = new File("D:/img/" + filename);
            byte[] bytes = file.getBytes();
            OutputStream outputStream = null;
            try {
                outputStream = new FileOutputStream(dest);
                outputStream.write(bytes);
            } finally {
                if (outputStream != null) {
                    outputStream.close();
                }
            }
          /*  file.transferTo(dest);
*/
            // 返回图片 URL
            return "http://example.com/upload/" + filename;
        }
    }

}
